package com.easy.interceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的token
        String token=request.getHeader(SYS.TOKEN_AUTHORIZATION);

        response.setContentType("application/json;charset=UTF-8");
        //判断token是否存在且有效
        if (token==null||!TokenUtil.verify( token)){
           /* response.setStatus(401);*/

            Result result=new Result(401,"认证异常",null);
            //hutool
           String json= JSONUtil.toJsonStr(result);
            //fastjson
           json= JSON.toJSONString( result);
            //返回结果
           response.getWriter().print(json);
            return false;
        }
        //放行
        return true;



    }
}
